package com.skycan.plc.adapter.netty.handler;

import com.skycan.plc.adapter.service.DeviceService;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.bytes.ByteArrayDecoder;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * 设备通道初始化器
 */
public class DeviceChannelInitializer extends ChannelInitializer<SocketChannel> {
    private static final Logger logger = LoggerFactory.getLogger(DeviceChannelInitializer.class);

    private final DeviceService deviceService;

    public DeviceChannelInitializer(DeviceService deviceService) {
        this.deviceService = deviceService;
    }

    @Override
    protected void initChannel(SocketChannel ch) {
        logger.info("新的设备连接: {}", ch.remoteAddress());

        ch.pipeline().addLast(
                // 心跳检测 - 60秒没有读写操作，触发IdleStateEvent
                new IdleStateHandler(60, 60, 0, TimeUnit.SECONDS),
                // 解码器 - 将ByteBuf解码为byte[]
                new ByteArrayDecoder(),
                // 编码器 - 将byte[]编码为ByteBuf
                new ByteArrayEncoder(),
                // 消息解码器 - 将byte[]解码为设备消息
                new DeviceMessageDecoder(),
                // 消息处理器 - 处理设备消息
                new DeviceMessageHandler(deviceService));
    }
}